package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.config.BusinessException;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService secKillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private VoucherOrderServiceImpl voucherOrderServiceImpl;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private IVoucherOrderService proxy;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT ;

    static {
        SECKILL_SCRIPT  = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是准备执行的
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    // 用于线程池处理的任务
    // 当初始化完毕后，就会去从对列中去拿信息
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    //1.获取队列中的订单信息
                    List<MapRecord<String, Object, Object>> voucherOrderList =
                            stringRedisTemplate.opsForStream().
                                    read(Consumer.from("group.orders", "consumer.orders"),
                                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed()));

                    //2.判断订单信息是否为空
                    if (Objects.isNull(voucherOrderList) || voucherOrderList.isEmpty()) {
                        //如果为null，说明没有消息，继续下一次循环,  进入阻塞等待
                        continue;
                    }
                    //3.获取订单信息
                    MapRecord<String, Object, Object> record = voucherOrderList.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 4.创建订单
//                    handleVoucherOrder(voucherOrder);
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "group.order", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }
    }
        private void handlePendingList() {
            while (true){
                try {
                    // 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().
                            read(Consumer.from("group.orders", "consumer.orders"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0")));

                    // 2.判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有异常消息，结束循环
                        break;
                    }
                    // 3.获取订单信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "group.orders", record.getId());
                }catch (Exception e){
                    log.error("处理pendding订单异常", e);
                    try{
                        Thread.sleep(20);
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
            }
        }
    }
        private void handleVoucherOrder(VoucherOrder voucherOrder){
            //获取用户
            Long userId = voucherOrder.getUserId();
            Long voucherId = voucherOrder.getVoucherId();

            //创建锁对象(新增代码)
            RLock redisLock = redissonClient.getLock("lock:order:" + userId);
            //2.判断是否获取锁成功
            boolean tryLock = redisLock.tryLock();
            if (!tryLock){
                //获取锁失败，直接返回失败或者重试
                log.error("不允许重复下单");
                return;
            }
            try {
                //获取代理对象（事务）
                proxy.createVoucherOrder(voucherOrder);

            }finally {
                //释放锁
                redisLock.unlock();
            }
        }

        // 阻塞队列
        private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);


    /**
     * redis消息队列解决版本
     * @param voucherId
     * @return
     */
    @Override
    public Result secKillVoucher(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        Long orderId = redisIdWorker.nextId("order");
        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),orderId.toString()
        );
        //lua脚本执行结果
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            if (r == 3){
                throw new BusinessException("优惠券库存异常，请不要再试");
            }
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单lua");
        }
        // 2.2.为0 ，有购买资格，把下单信息保存到redis消息队列（脚本执行的时候已经保存完成）

        proxy = (IVoucherOrderService)AopContext.currentProxy();
        //todo 另一个线程去处理订单信息

        // 3.返回订单id
        return Result.ok(orderId);
    }

/*    阻塞队列版本
@Override
    public Result secKillVoucher(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            if (r == 3){
                throw new BusinessException("优惠券库存异常，请不要再试");
            }
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 2.2.为0 ，有购买资格，把下单信息保存到阻塞队列
        long orderId = redisIdWorker.nextId("order");
        // TODO 保存阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        orderTasks.add(voucherOrder);
        proxy = (IVoucherOrderService)AopContext.currentProxy();
        // 3.返回订单id
        return Result.ok(orderId);
    }*/


/*    @Override
    public Result secKillVoucher(Long voucherId) {

        SeckillVoucher voucher = secKillVoucherService.getById(voucherId);

        if (Objects.isNull(voucher)){
            throw new BusinessException("优惠券不存在");
        }

        if (voucher.getBeginTime().isAfter(LocalDateTime.now())){
            throw new BusinessException("优惠券秒杀未开始");
        }

        if (voucher.getEndTime().isBefore(LocalDateTime.now())){
            throw new BusinessException("优惠券秒杀已过期");
        }

        if (voucher.getStock() < 1){
            throw new BusinessException("优惠券库存不足");
        }
        Long userId = UserHolder.getUser().getId();

        //创建锁对象(新增代码)
//        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);

        RLock lock = redissonClient.getLock("order:" + userId);


//        boolean tryLock = simpleRedisLock.tryLock(100L);

        boolean tryLock = lock.tryLock();
        //判断是否获取锁成功
        if (!tryLock){
            //获取锁失败，直接返回失败或者重试
            return Result.fail("一人一单");
        }

        try {
            //获取代理对象（事务）
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return voucherOrderServiceImpl.createVoucherOrder(voucherId);
//            return proxy.createVoucherOrder(voucherId);
//            return createVoucherOrder(voucherId);
        }finally {
            //释放锁
//            simpleRedisLock.unlock();
            lock.unlock();
        }

//        synchronized (userId.toString().intern()){
            //获取代理对象（事务）
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return voucherOrderServiceImpl.createVoucherOrder(voucherId);
//            return proxy.createVoucherOrder(voucherId);
//            return createVoucherOrder(voucherId);
//        }

    }*/


    /**
     * 阻塞线程版本创建订单
     * @param voucherOrder
     * @return
     */
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {

        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //判断
        if (count > 0){
            // 已经购买过
            throw new BusinessException("一人一单");
        }
        // 扣减库存
        boolean update = secKillVoucherService.update().
                setSql("stock = stock - 1").
                eq("voucher_id", voucherId).
//                update();
        gt("stock", 0).update();  //解决超卖问题，乐观锁

        if (!update){
            throw new BusinessException("库存不足");
        }

        save(voucherOrder);

    }

/*    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //判断
        if (count > 0){
            // 已经购买过
            return Result.fail("一人一单");
        }
        // 扣减库存
        boolean update = secKillVoucherService.update().
                setSql("stock = stock - 1").
                eq("voucher_id", voucherId).
//                update();
                gt("stock", 0).update();  //解决超卖问题，乐观锁

        if (!update){
            return Result.fail("库存不足");
        }

        // 生成订单
        VoucherOrder voucherOrder = new VoucherOrder();

        // 订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);

        // 优惠券id
        voucherOrder.setVoucherId(voucherId);

        save(voucherOrder);
        return Result.ok(orderId);
    }*/
}
